import { prisma } from '@/app/lib/prisma';
import { UserDTO } from '@/app/types/api';

export class UserService {
  static async findById(id: string): Promise<UserDTO | null> {
    const user = await prisma.user.findUnique({
      where: { id }
    });

    if (!user) return null;

    return {
      id: user.id,
      email: user.email,
      name: user.name,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString()
    };
  }

  static async findMany(params: { cursor?: string; limit?: number }): Promise<{
    users: UserDTO[];
    nextCursor?: string;
  }> {
    const { cursor, limit = 10 } = params;

    const users = await prisma.user.findMany({
      take: limit + 1,
      cursor: cursor ? { id: cursor } : undefined,
      orderBy: { createdAt: 'desc' }
    });

    const hasMore = users.length > limit;
    const nextCursor = hasMore ? users[limit - 1].id : undefined;
    const usersToReturn = hasMore ? users.slice(0, -1) : users;

    return {
      users: usersToReturn.map(user => ({
        id: user.id,
        email: user.email,
        name: user.name,
        createdAt: user.createdAt.toISOString(),
        updatedAt: user.updatedAt.toISOString()
      })),
      nextCursor
    };
  }
}